<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="150px"
    >
      <el-form-item label="半成品工单号" prop="workOrderNo">
        <el-input
          v-model="queryParams.workOrderNo"
          placeholder="请输入半成品工单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="物料编号/名称" prop="material">
        <el-input
          v-model="queryParams.material"
          placeholder="请输入物料编号或名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="物料规格" prop="specification">
        <el-input
          v-model="queryParams.specification"
          placeholder="请输入物料规格"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="物料型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入物料型号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="销售单号" prop="salesOrderNo">
        <el-input
          v-model="queryParams.salesOrderNo"
          placeholder="请输入销售单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="principal">
        <el-input
          v-model="queryParams.principal"
          placeholder="请输入负责人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creator">
        <el-input
          v-model="queryParams.creator"
          placeholder="请输入创建人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="客户订单编号" prop="customerOrderNo">
        <el-input
          v-model="queryParams.customerOrderNo"
          placeholder="请输入客户订单编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTimeRange">
        <el-date-picker
          v-model="queryParams.createTimeRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="质检状态" prop="inspectionStatus">
        <el-select
          v-model="queryParams.inspectionStatus"
          placeholder="请选择质检状态"
          clearable
          class="!w-180px"
        >
          <el-option label="待检" value="pending" />
          <el-option label="合格" value="passed" />
          <el-option label="不合格" value="failed" />
        </el-select>
      </el-form-item>
      <el-form-item label="完工状态" prop="completionStatus">
        <el-select
          v-model="queryParams.completionStatus"
          placeholder="请选择完工状态"
          clearable
          class="!w-180px"
        >
          <el-option label="未开始" value="notStarted" />
          <el-option label="进行中" value="inProgress" />
          <el-option label="已完成" value="completed" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户交期" prop="deliveryTimeRange">
        <el-date-picker
          v-model="queryParams.deliveryTimeRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="外协状态" prop="outsourcingStatus">
        <el-select
          v-model="queryParams.outsourcingStatus"
          placeholder="请选择外协状态"
          clearable
          class="!w-180px"
        >
          <el-option label="未外协" value="none" />
          <el-option label="外协中" value="inProgress" />
          <el-option label="已外协" value="completed" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:customer:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:customer:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      width="100px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column width="60" label="选择" type="selection" />
      <el-table-column label="半成品工单号" align="center" prop="workOrderNo" width="140px" />
      <el-table-column label="紧急程度" align="center" prop="priority" width="100px"/>
      <el-table-column label="生产类型" align="center" prop="productionType" width="110px"/>
      <el-table-column label="工单状态" align="center" prop="status" width="100px"/>
      <el-table-column label="领料状态" align="center" prop="materialPickingStatus" width="100px"/>
      <el-table-column label="质检状态" align="center" prop="inspectionStatus" width="100px"/>
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        min-width="120px"
        show-overflow-tooltip
      />
      <el-table-column label="基本单位" align="center" prop="baseUnit" width="100px" />
      <el-table-column label="基本数量" align="center" prop="baseQuantity" width="100px" />
      <el-table-column label="辅助单位" align="center" prop="auxiliaryUnit" width="100px" />
      <el-table-column label="客户交期" align="center" prop="deliveryDate" width="110px" />
      <el-table-column label="入库状态" align="center" prop="storageStatus" width="100px" />
      <el-table-column label="机台状态" align="center" prop="machineStatus" width="100px" />
      <el-table-column label="颜色" align="center" prop="color" width="100px" />
      <el-table-column label="完工状态" align="center" prop="completionStatus" width="100px" />
      <el-table-column label="已入库数量" align="center" prop="storageQuantity" width="120px" />
      <el-table-column label="需求数量" align="center" prop="requiredQuantity" width="120px" />

      <el-table-column label="完工时间" align="center" prop="completionTime" width="120px" />

      <el-table-column label="操作" align="center" fixed="right" width="200px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:customer:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:customer:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <semiFinishedProductsFrom ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
import { StockApi, DictItemConfigVO } from '@/api/erp/stock/stock'
import semiFinishedProductsFrom from './semiFinishedProductsFrom.vue'

/** ERP 客户 列表 */
defineOptions({ name: 'Customer' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<CustomerVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  workOrderNo: undefined,
  materialKey: undefined,
  materialSpec: undefined,
  materialModel: undefined,
  saleOrderNo: undefined,
  principal: undefined,
  creator: undefined,
  customerOrderNo: undefined,
  createTimeRange: [],
  inspectionStatus: undefined,
  completionStatus: undefined,
  deliveryTimeRange: [],
  outsourcingStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CustomerApi.getCustomerPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 选中操作 */
const selectionList = ref<any[]>([])
const handleSelectionChange = (rows: any[]) => {
  selectionList.value = rows
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const customerStatusOptions = ref<{ value: string; label: string }[]>([])
const customerSourceOptions = ref<{ value: string; label: string }[]>([])
const clueCategoryOptions = ref<{ value: string; label: string }[]>([])
const customerLevelOptions = ref<{ value: string; label: string }[]>([])
const negotiationProgressOptions = ref<{ value: string; label: string }[]>([])
const customerCategoryOptions = ref<{ value: string; label: string }[]>([])

const getdictItemData = async () => {
  const data = {
    dictCode: 'customer_source'
  }
  const cusStatus = { dictCode: 'customer_status' }
  const clueCategory = { dictCode: 'clue_category' }
  const customerLevel = { dictCode: 'customer_level' }
  const negotiationProgress = { dictCode: 'negotiation_progress' }
  const customerCategory = { dictCode: 'customer_category' }

  const response = await StockApi.getByDictCode(data)
  customerSourceOptions.value = response.map((item) => ({
    value: item.id,
    label: item.description
  }))
  const statusRes = await StockApi.getByDictCode(cusStatus)
  customerStatusOptions.value = statusRes.map((item) => ({
    value: item.id,
    label: item.description
  }))
  const clueCategoryRes = await StockApi.getByDictCode(clueCategory)
  clueCategoryOptions.value = clueCategoryRes.map((item) => ({
    value: item.id,
    label: item.description
  }))
  const customerLevelRes = await StockApi.getByDictCode(customerLevel)
  customerLevelOptions.value = customerLevelRes.map((item) => ({
    value: item.id,
    label: item.description
  }))
  const negotiationProgressRes = await StockApi.getByDictCode(negotiationProgress)
  negotiationProgressOptions.value = negotiationProgressRes.map((item) => ({
    value: item.id,
    label: item.description
  }))
  const customerCategoryRes = await StockApi.getByDictCode(customerCategory)
  customerCategoryOptions.value = customerCategoryRes.map((item) => ({
    value: item.id,
    label: item.description
  }))
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerApi.deleteCustomer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CustomerApi.exportCustomer(queryParams)
    download.excel(data, 'ERP 客户.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getdictItemData()
})
</script>
